package i.i.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.concurrent.Executors;

import i.i.myapplication.AppDatabase;
import i.i.myapplication.MainActivity;
import i.i.myapplication.RegisterActivity;
import i.i.myapplication.User;

public class LoginActivity extends AppCompatActivity {

    private EditText etLoginId, etLoginPhone;
    private Button btnLogin, btnRegister;
    private AppDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        SharedPreferences prefs = getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
        String savedUserId = prefs.getString("userId", null);
        String savedPhoneNumber = prefs.getString("phoneNumber", null);

        if (savedUserId != null && savedPhoneNumber != null) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
            return;
        }

        etLoginId = findViewById(R.id.et_login_id);
        etLoginPhone = findViewById(R.id.et_login_phone);
        btnLogin = findViewById(R.id.btn_login);
        btnRegister = findViewById(R.id.btn_register);

        db = AppDatabase.getInstance(this);

        btnLogin.setOnClickListener(v -> {
            String userId = etLoginId.getText().toString().trim();
            String phoneNumber = etLoginPhone.getText().toString().trim();

            if (userId.isEmpty() || phoneNumber.isEmpty()) {
                Toast.makeText(this, "Please enter both ID and Phone Number", Toast.LENGTH_SHORT).show();
                return;
            }

            Executors.newSingleThreadExecutor().execute(() -> {
                User user = db.userDao().findByUserIdAndPhoneNumber(userId, phoneNumber);
                if (user != null) {
                    runOnUiThread(() -> {
                        prefs.edit()
                                .putString("userId", userId)
                                .putString("phoneNumber", phoneNumber)
                                .apply();

                        Toast.makeText(this, "Login Successful!", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(this, MainActivity.class));
                        finish();
                    });
                } else {
                    runOnUiThread(() -> Toast.makeText(this, "Login failed! ID or Phone incorrect", Toast.LENGTH_SHORT).show());
                }
            });
        });

        btnRegister.setOnClickListener(v -> {
            startActivity(new Intent(this, RegisterActivity.class));
        });
    }
}
